<template>
  <el-form ref="channelRestrictionForm" :model="channelRestrictionForm" label-width="100px">
    <el-button type="primary" size="small" @click="addRuleFn"><i class="el-icon-plus"></i></el-button>
    <el-row class="margin-20">
      <el-col :span="3">
        <el-form-item class="text-align-left" @click="addRuleFn()" label="通道规则:"></el-form-item>
      </el-col>

      <el-col :span="20" class="padding-right">
        <div v-for="(item, index, key) in channelRestrictionForm.conditions" :key="key">
          <el-row>
            <el-col :span="8">
              <el-form-item class="text-align-left">
                <el-select :value="item.conditionKey" placeholder="" @input="selectConditionTempletChangeFn($event, item.conditionKey, index, item)">
                  <el-option :label="v.conditionName" :value="v.conditionKey" v-for="(v, key) in conditionTemplet" :key="key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item class="text-align-left">
                <el-select  :value="item.operator" placeholder="" :disabled="item.subConditionShow" @input="operatorChangeFn($event, item.operator, item)">
                  <el-option :label="v" :value="v" v-for="(v, key) in item.operatorList"  :key="key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="1" v-if="item.operator !== 'in' && item.operator !== '' && item.operator != undefined">
              <el-form-item class="text-align-left" >a=</el-form-item>
            </el-col>
            <el-col :span="4" v-if="item.operator !== 'in' && item.operator !== '' && item.operator != undefined ">
              <el-form-item v-if="item.conditionKey === 'TRADE_TIME_REGION'" class="text-align-left">
                <el-time-picker class="width100"
                  :disabled="item.subConditionShow"
                  :value = "item.params[0]| setTimes"
                  size="small"
                  :picker-options="{
                    selectableRange: '00:00:00 - 23:59:59'
                  }"
                  @input="getTimes($event,item,0)"
                  placeholder="">
                </el-time-picker>
              </el-form-item>
              <el-form-item v-else-if="item.conditionKey === 'WITHHOLD_TYPE' " class="text-align-left">
                <el-select v-model="item.params[0]" :disabled="item.subConditionShow">
                  <el-option v-for="(v, i) in withholdTypeList" :key="i"  :label="v" :value="i">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-else class="text-align-left">
                <el-input size="small" v-model="item.params[0]" :disabled="item.subConditionShow" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" v-else-if="item.operator === 'in' && item.conditionKey === 'WITHHOLD_TYPE'">
              <el-select v-model="item.params" multiple :disabled="item.subConditionShow">
                <el-option v-for="(v, i, key) in withholdTypeList" :key="key"  :label="v" :value="i">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="1" v-if="item.operator !== 'eq' && item.operator !== 'in' && item.operator !== '' && item.operator != undefined  ">
              <el-form-item class="text-align-left">b=</el-form-item>
            </el-col>
            <el-col :span="4" v-if="item.operator !== 'eq' && item.operator !== 'in' && item.operator!== '' && item.operator != undefined ">
              <el-form-item v-if="item.conditionKey === 'TRADE_TIME_REGION'" class="text-align-left">
                <el-time-picker class="width100"
                  :disabled="item.subConditionShow"
                  :value = "item.params[1]| setTimes"
                  size="small"
                  :picker-options="{
                    selectableRange: '00:00:00 - 23:59:59'
                  }"
                  @input="getTimes($event,item,1)"
                  placeholder="">
                </el-time-picker>
              </el-form-item>
              <el-form-item v-else class="text-align-left">
                <el-input size="small" v-model="item.params[1]" :disabled="item.subConditionShow" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-form-item class="text-align-left">
                <el-button size="small" @click="subRuleFn(index)">
                  <i class="el-icon-minus"></i>
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>

          <div v-if="item.subConditionShow" class="border">
            <el-row v-for="(itm, inx, key) in item.additionalList" :key="key">
              <el-col :span="7">
                <el-form-item class="text-align-left">
                  <el-select placeholder="" :disabled="inx == 0" v-model="itm.additionalValue" @change="additionalValueChangeFn($event, item.additionalList[inx])">
                    <el-option label="默认" value=""></el-option>
                    <el-option :label="itemChild.bankName" :value="itemChild.bankCode" v-for="(itemChild, key) in allBankList" :key="key"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item class="text-align-left">
                  <el-select v-model="itm.operator" placeholder="">
                    <el-option :label="v" :value="v" v-for="(v, key) in itm.operatorList" :key="key"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="1">
                <el-form-item class="text-align-left ">a=</el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item class="text-align-left">
                  <el-input size="small" v-model="itm.params[0]" placeholder="请输入内容"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="1" v-if="itm.operator !== 'eq'">
                <el-form-item class="text-align-left ">b=</el-form-item>
              </el-col>
              <el-col :span="3" v-if="itm.operator !== 'eq'">
                <el-form-item class="text-align-left">
                  <el-input size="small" v-model="itm.params[1]" placeholder="请输入内容"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item class="text-align-left">
                  <el-button size="small" :span="12" @click="subSonRuleFn(item.additionalList, inx, itm.additionalValue)"><i class="el-icon-minus"></i></el-button>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item class="text-align-left">
                  <el-button size="small" :span="12" @click="addSonRuleFn(item.additionalList, inx)"><i class="el-icon-plus"></i></el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

      </el-col>
    </el-row>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">确定</el-button>
      <el-button @click="onCanel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
  import { getChannelCondition, getOperatorList, getConditionTemplet, supportedBank, updateChannelCondition, getWithholdType } from '@/services/getData'
  import { OutputLowercase } from '@/common/mUtils'
  export default {
    name: 'channel-restriction-edit',
    data() {
      return {
        ruleItems: [],
        operatorList: {},
        channelRestrictionForm: {
          "conditions": [{
            "ruleKey": "",
            "conditionKey": "",
            "operator": "",
            "params": [],
            "params1": [],
            "additionalList": [{
              "conditionId": null,
              "operator": "",
              "additionalKey": "",
              "additionalValue": "",
              "params": []
            }]
          }]
        },
        defaultChannelRestrictionForm: {
          "conditions": [{
            "ruleKey": "",
            "conditionKey": "",
            "operator": "",
            'operatorList': [],
            "params": [],
            "additionalList": [{
              "conditionId": null,
              "operator": "",
              "additionalKey": "",
              "additionalValue": "",
              "params": [],
              "operatorList": ["(a,b)", "[a,b)", "(a,b]", "[a,b]", "a)(b", "a](b", "a)[b", "a][b"]
            }]
          }]
        },
        defaultConditions: {
          "ruleKey": "",
          "conditionKey": "",
          "operator": "",
          "subConditionShow": false,
          "params": [],
          "additionalList": [{
            "conditionId": null,
            "operator": "",
            "operatorList": ["(a,b)", "[a,b)", "(a,b]", "[a,b]", "a)(b", "a](b", "a)[b", "a][b"],
            "additionalKey": "",
            "additionalValue": "",
            "params": []
          }],
          'operatorList': []
        },
        defaultAdditionalList: {
          "conditionId": null,
          "operator": "",
          "additionalKey": "",
          "additionalValue": "",
          "params": [],
          "operatorList": ["(a,b)", "[a,b)", "(a,b]", "[a,b]", "a)(b", "a](b", "a)[b", "a][b"]
        },
        conditionTemplet: [],
        allBankList: [],
        conditionKeySupportAdditional: {}, // 是否支持额外条件字段
        bankListObj: {},
        withholdTypeList: [], // 支付类型
        operatorObj: {}
      }
    },
    props: {
      channelFormData: {
        type: Object,
        default() {
          return {
            channelCode: "", // 通道别名,
            channelName: "", // 通道中文名称,
            tradeType: 1, // 交易类型,
            authentication: 1, // 是否需要鉴权,
            authenticationType: 1, // 鉴权类型
            priority: 1, // 优先级
            remark: "111111" // 备注ss: new Date().getTime()
          }
        }
      },
      rmd: {
        type: Number,
        default: 0
      }
    },
    watch: {
      rmd: function() {
        let defaultChannelRestrictionForm = JSON.parse(JSON.stringify(this.defaultChannelRestrictionForm))
        this.channelRestrictionForm = Object.assign({}, defaultChannelRestrictionForm)
        this.supportedBankList()
        this.initData()
      }
    },
    created() {
      this.tradeTypeItems = this.GLOBAL.getChanelType()
      this.getAuthenticationType = this.GLOBAL.getAuthenticationType()
      this.initConditionTemplet()
      this.supportedBankList()
      this.initData()
      this.az()
      this.getWithholdTypeFn()
    },
    filters: {
      setTimes (time) {
        if(!time){
          return ''
        }
        var strA = time.split(':')
        return  new Date(2016, 9, 1, strA[0], strA[1])
      }
    },
    methods: {
      getTimes (time, item, index) {
        let  h = time.getHours()
        let  m = time.getMinutes()
        item.params[index] = h + ':' + m
       this.channelRestrictionForm = JSON.parse(JSON.stringify(this.channelRestrictionForm))
      },
      // 添加通道限制条件
      addRuleFn() {
        let defaultConditions = JSON.parse(JSON.stringify(this.defaultConditions))
        this.channelRestrictionForm.conditions.push(Object.assign({}, defaultConditions))
      },

      // 删除当前通道限制条件
      subRuleFn(i) {
        this.channelRestrictionForm.conditions.splice(i, 1)
      },

      // 当规则变化时，是否支持额外字段也要变化
      selectConditionTempletChangeFn(e, key, i, v) {
        if (e !== key) {
          v.operator = ''
          v.conditionKey = e
        }
        v.conditionName = this.operatorObj[e]
        v.operatorList = this.initOperatorList(e)
        if(this.conditionKeySupportAdditional[e] == 1) {
          if( !v.additionalList ){
            v.additionalList = []
            let defaultAdditionalList = JSON.parse(JSON.stringify(this.defaultAdditionalList))
            v.additionalList.push(defaultAdditionalList)
          }
          v.subConditionShow = true
        } else {
          v.subConditionShow = false
        }
        this.channelRestrictionForm = JSON.parse(JSON.stringify(this.channelRestrictionForm))
      },
      onSubmit() {
        let params = {}
        params['operatorName'] = sessionStorage.getItem('ms_username')
        params['operatedMenu'] = "代收通道管理"
        params['operatedButton'] = "编辑通道限制条件按钮"
        params['channelCode'] = this.channelFormData.channelCode
        params['tradeType'] = this.channelFormData.tradeType
        params["conditions"] = []
        let length = this.channelRestrictionForm.conditions.length
        for(let i = 0; i < length; i++) {
          let conditionLsit = {}
          if(this.channelRestrictionForm.conditions[i].subConditionShow == true) {
            let num = 0
            for (let k in this.channelRestrictionForm.conditions[i].additionalList) {
              if (this.channelRestrictionForm.conditions[i].additionalList[k].additionalValue === '') {
                num++
              }
            }
            if (num === 0) {
              this.$message({
                type: 'error',
                message: "单日单卡金额限制和单卡单笔金额限制必须要有默认规则"
              });
              return false
            }
            conditionLsit.additionalList = this.channelRestrictionForm.conditions[i].additionalList
            conditionLsit.ruleKey = this.channelRestrictionForm.conditions[i].ruleKey
            conditionLsit.conditionKey = this.channelRestrictionForm.conditions[i].conditionKey
            conditionLsit.conditionName = this.channelRestrictionForm.conditions[i].conditionName
          } else {
            conditionLsit.ruleKey = this.channelRestrictionForm.conditions[i].ruleKey
            conditionLsit.conditionKey = this.channelRestrictionForm.conditions[i].conditionKey
            conditionLsit.conditionName = this.channelRestrictionForm.conditions[i].conditionName
            conditionLsit.conditionId = this.channelRestrictionForm.conditions[i].conditionId
            conditionLsit.operator = this.channelRestrictionForm.conditions[i].operator
            conditionLsit.additionalKey = this.channelRestrictionForm.conditions[i].additionalKey
            conditionLsit.additionalValue = this.channelRestrictionForm.conditions[i].additionalValue
            conditionLsit.params = this.channelRestrictionForm.conditions[i].params
          }
          params["conditions"].push(conditionLsit)
        }
        updateChannelCondition(params).then(
          res => {
            if(res.resultCode == 1) {
              this.$message({
                type: 'success',
                message: "提交成功"
              });
              this.$emit("chanelClose", 3)
            } else {
              this.$message({
                type: 'error',
                message: res.errorDesc
              });
            }
          }
        )
      },
      onCanel() {
        this.$emit("chanelClose", 3, "cancel")
      },

      // 额外限制条件增加
      addSonRuleFn(v, i) {
        let defaultAdditionalList = JSON.parse(JSON.stringify(this.defaultAdditionalList))
        v.push(Object.assign({}, defaultAdditionalList))
      },

      // 额外限制条件删除
      subSonRuleFn(v, i, l) {
        if(l == '') {
          this.$message({
            type: 'warning',
            message: "默认字段不可删除"
          });
          return false;
        }
        v.splice(i, 1)
      },

      // 初始化数据
      async initData() {
        try {
          const res = await getChannelCondition({
            channelCode: this.channelFormData.channelCode,
            tradeType: this.channelFormData.tradeType
          })
          if(res.resultCode == 1) {
            let that = this;
            this.defaultConditions.ruleKey = res.data.ruleKey
            res.data.conditions.forEach(item => {
              if(that.conditionKeySupportAdditional[item.conditionKey] == 1) {
                item.subConditionShow = true
                item.operator = ''
                item.params = []
              } else {
                item.subConditionShow = false
              }
            })
            this.channelRestrictionForm.conditions = res.data.conditions
          } else {
            throw new Error(res.message)
          }
        } catch(err) {
          console.log('获取数据失败', err)
        }
      },

      // 查询操作符列表
      initOperatorList (v) {
        return v === undefined ? this.operatorList : this.operatorList[v]
      },

      // 查询限制条件模板列表
      async initConditionTemplet() {
        try {
          const res = await getConditionTemplet({
            ruleType: 1
          })
          if(res.resultCode == 1) {
            res.rows.forEach(item => {
              this.conditionKeySupportAdditional[item.conditionKey] = item.supportAdditional
              let tempOperateObj = {}
              tempOperateObj[item.conditionKey] = item.operatorList
              Object.assign(this.operatorList, tempOperateObj)
              let aa = {}
              aa[item.conditionKey] = item.conditionName
              Object.assign(this.operatorObj, aa)
            })
            this.conditionTemplet = res.rows
          } else {
            throw new Error(res.message)
          }
        } catch(err) {
          console.log('获取数据失败', err)
        }
      },

      // 加载支持的银行列表
      async supportedBankList(tradeType, bankCode) {
        try {
          const res = await supportedBank({
            tradeType: tradeType,
            operatorName: sessionStorage.getItem('ms_username'),
            operatedMenu: "代收通道管理",
            operatedButton: "",
            channelCode: this.channelFormData.channelCode,
            tradeType: this.channelFormData.tradeType
          })
          if(res.resultCode == 1) {
            this.allBankList = res.bankList
          } else {
            throw new Error(res.message)
          }
        } catch(err) {
          console.log('获取数据失败', err)
        }
      },
      additionalValueChangeFn (v, i) {
        i.additionalKey = this.formatBankList(v)
      },

      // 查询支付类型
      async getWithholdTypeFn () {
        try {
          const res = await getWithholdType()
          if (res.resultCode == 0) {
            this.$message({
              type: 'error',
              message: res.errorDesc
            });
          } else {
            this.withholdTypeList = res
          }
        } catch(err) {
          console.log('获取数据失败', err)
        }
      },

      // 格式化银行卡列表将数组变成对象
      formatBankList (v) {
        let bankListObj = {}
        let bankName = ''
        let bankCode = ''
        let tempObj = {}
				const list = this.allBankList
				for (let i of list) {
					bankName = i.bankName
          bankCode = i.bankCode
          tempObj[bankCode] = bankName
					Object.assign(bankListObj, tempObj)
        }
        return v === undefined ? bankListObj : bankListObj[v]
      },

      //输出a-z  26个小写字母
      az(i) {
        return OutputLowercase(i)
      },
      operatorChangeFn (e, opt, v) {
        if (e !== opt) {
          v.params = []
          v.operator  = e
        }
        this.channelRestrictionForm = JSON.parse(JSON.stringify(this.channelRestrictionForm))
      }
    }
  }
</script>
<style lang="less">
  .text-align-left>.el-form-item__label {
    text-align: left;
  }

  .text-align-left>.el-form-item__content {
    margin-left: 0 !important;
    margin-right: 10px;
  }

  .border {
    border: dashed 1px lightgrey;
    padding-top: 10px;
    padding-left: 10px;
    margin-bottom: 30px;
  }

  .margin-20 {
    margin: 22px 0;
  }

  .padding-left-10 {
    padding-left: 20px;
  }

  .width100.el-date-editor.el-input {
    width: 100% !important;
  }
</style>
